import { areaData } from '../../../../config/index';
import { rejectAddress } from './util';

const labelsOptions = [
  {
    id: 0,
    name: '家',
  },
  {
    id: 1,
    name: '公司',
  },
];

const basePage = require('../../../../common/BasePage');
Page({
  behaviors: [basePage],
  options: {
    multipleSlots: true,
  },
  externalClasses: ['theme-wrapper-class'],
  data: {
    locationState: {
      detail: '',
      labelIndex: null,
      addressId: '',
      addressTag: '',
      cityCode: '',
      cityName: '',
      countryCode: '',
      countryName: '',
      detailAddress: '',
      districtCode: '',
      districtName: '',
      isDefault: false,
      name: '',
      phone: '',
      provinceCode: '',
      provinceName: '',
      isEdit: false,
      isOrderDetail: false,
      isOrderSure: false,
    },
    areaData: areaData,
    labels: labelsOptions,
    areaPickerVisible: false,
    submitActive: false,
    visible: false,
    labelValue: '',
    columns: 3,
  },
  privateData: {
    verifyTips: '',
  },
  onLoad(options) {
    const { id } = options;
    // this.init(id);
    if (id) {
      const addr = wx.getStorageSync('addr');
      // console.log('id addr', id, addr);
      if (addr && addr.address) {
        const arr = addr.address.split(' ');
        // console.log("arr", arr);

        // addr.address = arr[0];
        if (arr.length > 0) {
          addr.detail = arr[arr.length - 1];
          //arr移除最后一个元素
          arr.splice(arr.length - 1, 1);
          addr.address = arr.join(' ');
        }
      }
      this.setData({
        locationState: addr,
      });
    }
    // console.log('locationState', this.data.locationState);
  },

  onUnload() {
    if (!this.hasSava) {
      rejectAddress();
    }
  },

  hasSava: false,

  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    if (item === 'area') {
      const { selectedOptions = [] } = e.detail;
      console.log('地区', e.detail);
      this.setData({
        'locationState.provinceCode': selectedOptions[0].value,
        'locationState.province': selectedOptions[0].label,
        'locationState.city': selectedOptions[1].label,
        'locationState.cityCode': selectedOptions[1].value,
        'locationState.districtCode': selectedOptions[2].value,
        'locationState.district': selectedOptions[2].label,
        areaPickerVisible: false,
      });
    } else {
      const { value = '' } = e.detail;
      this.setData({
        [`locationState.${item}`]: value,
      });
    }
  },
  onPickArea() {
    this.setData({
      areaPickerVisible: true,
    });
  },
  onPickLabels(e) {
    const { item } = e.currentTarget.dataset;
    const {
      locationState: { labelIndex = undefined },
      labels = [],
    } = this.data;
    let payload = {
      labelIndex: item,
      addressTag: labels[item].name,
    };
    if (item === labelIndex) {
      payload = {
        labelIndex: null,
        addressTag: '',
      };
    }
    this.setData({
      'locationState.labelIndex': payload.labelIndex,
    });
    this.triggerEvent('triggerUpdateValue', payload);
  },
  addLabels() {
    this.setData({
      visible: true,
    });
  },
  confirmHandle() {
    const { labels, labelValue } = this.data;
    this.setData({
      visible: false,
      labels: [
        ...labels,
        {
          id: labels[labels.length - 1].id + 1,
          name: labelValue,
        },
      ],
      labelValue: '',
    });
  },
  cancelHandle() {
    this.setData({
      visible: false,
      labelValue: '',
    });
  },
  onCheckDefaultAddress({ detail }) {
    const { value } = detail;
    // return console.log('onCheckDefaultAddress', value);
    this.setData({
      'locationState.defaultAddr': value ? 0 : 1,
    });
  },

  builtInSearch({ code, name }) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting[code] === false) {
            wx.showModal({
              title: `获取${name}失败`,
              content: `获取${name}失败，请在【右上角】-小程序【设置】项中，将【${name}】开启。`,
              confirmText: '去设置',
              confirmColor: '#FA550F',
              cancelColor: '取消',
              success(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success(settinRes) {
                      if (settinRes.authSetting[code] === true) {
                        resolve();
                      } else {
                        console.warn('用户未打开权限', name, code);
                        reject();
                      }
                    },
                  });
                } else {
                  reject();
                }
              },
              fail() {
                reject();
              },
            });
          } else {
            resolve();
          }
        },
        fail() {
          reject();
        },
      });
    });
  },
  addr_click() {
    if (!this.data.locationState.longitude) {
      this.chooseLocation();
    }
  },
  /**通过城市获取当前省市县 */
  req_city(result) {
    this.request(
      {
        url: `${this.data.host}/v1/user-address/city`,
        method: 'post',
        data: {
          location: `${result.latitude},${result.longitude}`,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
      },
      (res) => {
        this.setData({
          'locationState.province': res.data.address_component.province,
          'locationState.city': res.data.address_component.city,

          'locationState.districtCode': res.data.ad_info.adcode,
          'locationState.district': res.data.address_component.district,
        });
      },
    );
  },
  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        console.log('选择位置', res);
        this.setData({
          'locationState.address': res.name,
          'locationState.latitude': res.latitude, //
          'locationState.longitude': res.longitude,
        });
        this.req_city(res);
      },
      fail: function (res) {
        console.warn(`wx.chooseLocation fail: ${JSON.stringify(res)}`);
        if (res.errMsg !== 'chooseLocation:fail cancel') {
          wx.showToast({
            title: JSON.stringify(res),

            icon: 'none',
          });
        }
      },
    });
  },
  onSearchAddress() {
    this.builtInSearch({
      code: 'scope.userLocation',
      name: '地址位置',
    }).then(() => {
      this.chooseLocation();
    });
  },
  formSubmit() {
    const { locationState } = this.data;
    console.log('locationState', locationState);
    this.hasSava = true;
    let url = '/v1/user-address';
    let method = 'post';
    if (locationState.sid) {
      url = `/v1/user-address/${locationState.sid}`;
      method = 'put';
    }
    this.request(
      {
        url: this.data.host + url,
        method: method,
        data: {
          address: `${locationState.address} ${locationState.detail}`,
          city: locationState.city,
          defaultAddr: locationState.defaultAddr,
          district: locationState.district,
          districtCode: locationState.districtCode,
          latitude: locationState.latitude,
          longitude: locationState.longitude,
          memberName: locationState.memberName,
          memberPhone: locationState.memberPhone,
          province: locationState.province,
          // "provinceCode": locationState.provinceCode,
        },
      },
      (res) => {
        wx.showToast({
          title: '保存成功',

          icon: 'success',
        });
        wx.navigateBack({
          delta: 1,
        });
      },
    );
    // resolveAddress({
    //   saasId: '88888888',
    //   uid: `88888888205500`,
    //   authToken: null,
    //   id: locationState.addressId,
    //   addressId: locationState.addressId,
    //   phone: locationState.phone,
    //   name: locationState.name,
    //   countryName: locationState.countryName,
    //   countryCode: locationState.countryCode,
    //   provinceName: locationState.provinceName,
    //   provinceCode: locationState.provinceCode,
    //   cityName: locationState.cityName,
    //   cityCode: locationState.cityCode,
    //   districtName: locationState.districtName,
    //   districtCode: locationState.districtCode,
    //   detailAddress: locationState.detailAddress,
    //   isDefault: locationState.isDefault === 1 ? 1 : 0,
    //   addressTag: locationState.addressTag,
    //   latitude: locationState.latitude,
    //   longitude: locationState.longitude,
    //   storeId: null,
    // });
  },
});
